package com.huobiinfo.demo.webmagic;

import com.huobiinfo.demo.model.News;
import com.huobiinfo.demo.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author peter
 * @title: MySqlPipeline
 * @projectName huobiinfo_webmagic_springboot
 * @description: 自定义实现Pipleline接口
 * @date 19-6-14下午2:35
 */
@Component
public class MySqlPipeline implements Pipeline {

    private NewsService newsService;

    @Autowired
    public void setNewsService(NewsService newsService) {
        this.newsService = newsService;
    }

   /* public MySqlPipeline() {
    }*/

    @Override
    public void process(ResultItems resultItems, Task task) {

        Map<String, Object> mapRsults = resultItems.getAll();

        Iterator<Map.Entry<String, Object>> iterator = mapRsults.entrySet().iterator();

        Map.Entry<String, Object> entry;

        //输出到控制台
        while (iterator.hasNext()) {
            entry = iterator.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        //持久化
        News news = new News();
        if (!mapRsults.get("Title").equals("")) {
            if (mapRsults.get("Content") != null) {
                news.setTitle((String) mapRsults.get("Title"));
                news.setContent((String) mapRsults.get("Content"));
            } else {
                System.out.println("content**************null***********************");
            }
        }

        try {
            int i = newsService.insert(news);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
